<script setup>
import { onMounted, ref, reactive } from 'vue';
import { getUserOrderAPI, confirmReceiptAPI } from '@/apis/order';
import { addCommentAPI } from '@/apis/comment';
// import { useRouter } from 'vue-router';
// const router = useRouter()
import dayjs from 'dayjs'

const formatTime = (timeString) => {
  return dayjs(timeString).format('YYYY年M月D日 HH:mm:ss')
}
// tab列表
const tabTypes = [
  { name: "all", label: "全部订单" },
  { name: "unpay", label: "待付款" },
  { name: "deliver", label: "待发货" },
  { name: "receive", label: "待收货" },
  { name: "comment", label: "待评价" },
  { name: "complete", label: "已完成" },
  { name: "cancel", label: "已取消" }
]

// 获取订单列表
const orderList = ref([])
const total = ref(0)
const params = ref({
  status: 0,
  page: 1,
  pageSize: 2
})
const getOrderList = async () => {
  const res = await getUserOrderAPI(params.value)
  console.log(res);
  orderList.value = res.data.data
  total.value = res.data.data.counts
}


onMounted(() => getOrderList())

//tab切换
const tabChange = (type) => {
  params.value.page = 1
  params.value.status = type
  getOrderList()
}

//页数切换
const pageChange = (page) => {
  params.value.page = page
  getOrderList()
}

// 创建格式化函数
const formatPayState = (payState) => {
  const stateMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '待评价',
    5: '已完成',
    6: '已取消'
  }
  return stateMap[payState]
}

const confirmReceipt = async (id) => {
  await confirmReceiptAPI(id)
  getOrderList()
}

const isEvaluation = ref(false)
const evaluationGoodsId = ref()
const evaluationContent = ref()
const orderItemId = ref()
const openEvaluationDialog = (goodsId, id) => {
  evaluationGoodsId.value = goodsId
  orderItemId.value = id
  isEvaluation.value = true
}

const evaluationGoods = async () => {
  if (!evaluationContent.value.trim()) {
    ElMessage.error('评价内容不能为空')
    return
  }
  try {
    let submitData = reactive({
      orderItemId: orderItemId.value,
      goodsId: evaluationGoodsId.value,
      content: evaluationContent.value,
      parentId: null,
      parentUsername: '',
      level: '0'
    })
    await addCommentAPI(submitData)
    ElMessage.success('评价成功')
    isEvaluation.value = false
    evaluationContent.value = ''
    // 刷新数据
    getOrderList()
  } catch (error) {
    ElMessage.error('评价失败')
  }
}

</script>

<template>
  <div class="order-container">
    <el-tabs @tab-change="tabChange">
      <!-- tab切换 -->
      <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" />

      <div class="main-container">
        <!-- <div class="holder-container" v-if="orderList.length === 0"> -->
        <div class="holder-container" v-if="false">
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList.items" :key="order.id">
            <div class="head">
              <span>下单时间：{{ formatTime(order.createTime) }}</span>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <span>订单编号：{{ order.id }}</span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.goodsList" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="item.goodsImg" alt="" />
                    </a>
                    <div class="info">
                      <p class="name">
                        {{ item.goodsName }}
                      </p>
                    </div>
                    <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                    <div class="count">x{{ item.amount }}</div>
                    <div class="column state">
                      <p>{{ formatPayState(item.state) }}</p>
                    </div>
                  </li>
                </ul>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.total?.toFixed(2) }}</p>
                <p>（含运费：¥{{ order.shippingFee?.toFixed(2) }}）</p>
                <p>在线支付</p>
              </div>
              <ul>
                <li v-for="item in order.goodsList" :key="item.id">
                  <div class="column action">
                    <p v-if="item.state === 1">
                      <a href="javascript:;" class="green"
                        @click="$router.push({ path: '/pay', query: { id: order.id } })">立即付款</a>
                    </p>
                    <p v-if="item.state === 2">
                      <a href="javascript:;" class="green">等待发货</a>
                    </p>
                    <p v-if="item.state === 3">
                      <a href="javascript:;" class="green" @click="confirmReceipt(item.id)">确认收货</a>
                    </p>
                    <p v-if="item.state === 4">
                      <a href="javascript:;" class="green" @click="openEvaluationDialog(item.goodsId, item.id)">评价商品</a>
                    </p>
                    <p v-if="item.state === 5">
                      <a href="javascript:;" class="green" @click="$router.push(`/detail/${item.goodsId}`)">再次购买</a>
                    </p>
                    <p v-if="item.state === 6">
                      <a href="javascript:;" class="green" @click="$router.push(`/detail/${item.goodsId}`)">再次购买</a>
                    </p>
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination :total="total" @current-change="pageChange" v-model:page-size="params.pageSize" background
              layout="prev, pager, next" />
          </div>
        </div>
      </div>
    </el-tabs>
  </div>
  <!-- 开始评论 -->
  <el-dialog v-model="isEvaluation" title="评价商品" width="500">
    <el-form>
      <el-input v-model="evaluationContent" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
        placeholder="请在此输入评价" />
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isEvaluation = false">取消</el-button>
        <el-button type="primary" @click="evaluationGoods()">
          发表
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: center;
    justify-content: center;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      >p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        // align-self: center;


        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: center;
              padding: 0 10px;

              p {
                align-items: center;

                &.name {
                  height: 38px;
                  margin-top: 20px;
                  align-items: center;
                  justify-content: center;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
              margin-top: 20px;
            }

            .count {
              width: 80px;
              margin-top: 20px;
            }
          }
        }
      }

      &.state {
        width: 120px;
        margin-top: -10px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>